package com.liuqh.tag.poi;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.util.Units;
import org.apache.poi.xddf.usermodel.chart.AxisCrossBetween;
import org.apache.poi.xddf.usermodel.chart.AxisPosition;
import org.apache.poi.xddf.usermodel.chart.BarDirection;
import org.apache.poi.xddf.usermodel.chart.ChartTypes;
import org.apache.poi.xddf.usermodel.chart.LegendPosition;
import org.apache.poi.xddf.usermodel.chart.XDDFBarChartData;
import org.apache.poi.xddf.usermodel.chart.XDDFCategoryAxis;
import org.apache.poi.xddf.usermodel.chart.XDDFCategoryDataSource;
import org.apache.poi.xddf.usermodel.chart.XDDFChartLegend;
import org.apache.poi.xddf.usermodel.chart.XDDFDataSourcesFactory;
import org.apache.poi.xddf.usermodel.chart.XDDFNumericalDataSource;
import org.apache.poi.xddf.usermodel.chart.XDDFValueAxis;
import org.apache.poi.xwpf.usermodel.XWPFChart;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

/**
 * @Description TODO(这里用一句话描述这个类的作用)
 *
 * @author liuqinghua
 * @date 2023-4-23
 */
public class CreateWortTest {
	public static void main(String[] args) throws Exception {
		// 1、创建word文档对象
		File file = new File("d:\\word\\model.docx");
		InputStream inputStream = new FileInputStream(file);
		XWPFDocument document = new XWPFDocument(inputStream);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("${model}", "aaaaaaaaaaaaaaaaa");
		List<XWPFParagraph> paragraphs = document.getParagraphs();
		for (XWPFParagraph per : paragraphs) {
			List<XWPFRun> runs = per.getRuns();
			for (XWPFRun run : runs) {
				// 获取文本的值
				String text = run.getText(0);
				if (StringUtils.isNotEmpty(text)) {
					if (text.indexOf("Chart") != -1) {
//                        createSingleBar(document, run);
						createDoubleBar(document, run);
					} else {
						// 遍历map
						for (Map.Entry<String, Object> entry : map.entrySet()) {
							// 获取map的key
							String key = entry.getKey();
							// 判断文本的值和map的key，文本中是否有和key一样的占位符
							if (text.indexOf(key) != -1) {
								// 获取对应key的value
								Object value = entry.getValue();
								// 把文本的内容，key替换为value
								text = text.replace(key, value.toString());
								// 把替换好的文本内容，保存到当前这个文本对象
								run.setText(text, 0);
							}
						}
					}
				}
			}
		}

		// 10、输出到word文档
		FileOutputStream fos = new FileOutputStream("d:\\word\\test2.docx");
		document.write(fos); // 导出word

		// 11、关闭流
		fos.close();
		document.close();
	}

	/**
	 * @param document
	 * @param run
	 * @throws InvalidFormatException
	 * @throws IOException
	 */
	private static void createSingleBar(XWPFDocument document, XWPFRun run) throws Exception {
		run.setText("", 0);
		// 2、创建chart图表对象,抛出异常
		XWPFChart chart = document.createChart(run, 15 * Units.EMU_PER_CENTIMETER, 10 * Units.EMU_PER_CENTIMETER);
		chart.setChartTopMargin(1000L);
		// 3、图表相关设置
		chart.setTitleText("使用POI创建的柱状图"); // 图表标题
		chart.setTitleOverlay(false); // 图例是否覆盖标题

		// 4、图例设置
		XDDFChartLegend legend = chart.getOrAddLegend();
		legend.setPosition(LegendPosition.TOP); // 图例位置:上下左右

		// 5、X轴(分类轴)相关设置
		XDDFCategoryAxis xAxis = chart.createCategoryAxis(AxisPosition.BOTTOM); // 创建X轴,并且指定位置
		xAxis.setTitle("日期（年月）"); // x轴标题
		String[] xAxisData = new String[] { "2021-01", "2021-02", "2021-03", "2021-04", "2021-05", "2021-06", "2021-07",
				"2021-08", "2021-09", "2021-10", "2021-11", "2021-12", };
		XDDFCategoryDataSource xAxisSource = XDDFDataSourcesFactory.fromArray(xAxisData); // 设置X轴数据

		// 6、Y轴(值轴)相关设置
		XDDFValueAxis yAxis = chart.createValueAxis(AxisPosition.LEFT); // 创建Y轴,指定位置
		yAxis.setTitle("粉丝数（个）"); // Y轴标题
		yAxis.setCrossBetween(AxisCrossBetween.BETWEEN); // 设置图柱的位置:BETWEEN居中
		Integer[] yAxisData = new Integer[] { 10, 35, 21, 46, 79, 88, 39, 102, 71, 28, 99, 57 };
		XDDFNumericalDataSource<Integer> yAxisSource = XDDFDataSourcesFactory.fromArray(yAxisData); // 设置Y轴数据

		// 7、创建柱状图对象
		XDDFBarChartData barChart = (XDDFBarChartData) chart.createData(ChartTypes.BAR, xAxis, yAxis);
		barChart.setBarDirection(BarDirection.COL); // 设置柱状图的方向:BAR横向,COL竖向,默认是BAR

		// 8、加载柱状图数据集
		XDDFBarChartData.Series barSeries = (XDDFBarChartData.Series) barChart.addSeries(xAxisSource, yAxisSource);
		barSeries.setTitle("粉丝数", null); // 图例标题

		// 9、绘制柱状图
		chart.plot(barChart);
	}

	private static void createDoubleBar(XWPFDocument document, XWPFRun run) throws Exception {
		run.setText("", 0);
		// 2、创建chart图表对象,抛出异常
		XWPFChart chart = document.createChart(run, 15 * Units.EMU_PER_CENTIMETER, 10 * Units.EMU_PER_CENTIMETER);
		chart.setChartTopMargin(1000L);
		// 3、图表相关设置
		chart.setTitleText("使用POI创建的柱状图"); // 图表标题
		chart.setTitleOverlay(false); // 图例是否覆盖标题

		// 4、图例设置
		XDDFChartLegend legend = chart.getOrAddLegend();
		legend.setPosition(LegendPosition.TOP); // 图例位置:上下左右

		// 5、X轴(分类轴)相关设置
		XDDFCategoryAxis xAxis = chart.createCategoryAxis(AxisPosition.BOTTOM); // 创建X轴,并且指定位置
		xAxis.setTitle("日期（年月）"); // x轴标题
		String[] xAxisData = new String[] { "2021-01", "2021-02", "2021-03", "2021-04", "2021-05", "2021-06", "2021-07",
				"2021-08", "2021-09", "2021-10", "2021-11", "2021-12", };
		XDDFCategoryDataSource xAxisSource = XDDFDataSourcesFactory.fromArray(xAxisData); // 设置X轴数据

		// 6、Y轴(值轴)相关设置
		XDDFValueAxis yAxis = chart.createValueAxis(AxisPosition.LEFT); // 创建Y轴,指定位置
		yAxis.setTitle("粉丝数（个）"); // Y轴标题
		yAxis.setCrossBetween(AxisCrossBetween.BETWEEN); // 设置图柱的位置:BETWEEN居中
		Integer[] yAxisData = new Integer[] { 10, 35, 21, 46, 79, 88, 39, 102, 71, 28, 99, 57 };
		XDDFNumericalDataSource<Integer> yAxisSource = XDDFDataSourcesFactory.fromArray(yAxisData); // 设置Y轴数据

		// 7、创建柱状图对象
		XDDFBarChartData barChart = (XDDFBarChartData) chart.createData(ChartTypes.BAR, xAxis, yAxis);
		barChart.setBarDirection(BarDirection.COL); // 设置柱状图的方向:BAR横向,COL竖向,默认是BAR

		// 8、加载柱状图数据集
		XDDFBarChartData.Series barSeries = (XDDFBarChartData.Series) barChart.addSeries(xAxisSource, yAxisSource);
		barSeries.setTitle("粉丝数", null); // 图例标题

		// 9、绘制柱状图
		chart.plot(barChart);
	}

}
